/***************************************************************
*  Copyright (c) 2007 by GroupMe! Team (www.groupme.net)
*  All rights reserved.
*
*  This file is part of the GroupMe! Project. Source code of 
*  this project is closed and redistribution of this code is
*  prohibited. 
*  
*  Contact: http://www.groupme.net
*
*  This copyright notice MUST APPEAR in all copies of the file!
***************************************************************/
package net.groupme.utils.sql;

import java.net.MalformedURLException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import net.groupme.model.ObjectFactory;
import net.groupme.search.strategy.model.WeightedResource;

import org.springframework.jdbc.object.MappingSqlQuery;

/**
 * created on 19.12.2007
 * 
 * Small helper class to query scoring of resources.
 * 
 * @author Fabian Abel, <a href="mailto:abel@l3s.de">abel@l3s.de</a>
 * @author last edited by: $Author: mischa $
 * 
 * @version $Revision: 1.1 $ $Date: 2007-12-19 19:54:33 $
 */
public class GetWeightedResource extends MappingSqlQuery{
	/**
	 * Creates a new GetWeightedResource instance.
	 * @param ds the data source
	 * @param sql SQL query which has only a resourceId and a score column
	 */
	public GetWeightedResource(DataSource ds, String sql) {
		super(ds, sql);
	}

	/* (non-Javadoc)
	 * @see org.springframework.jdbc.object.MappingSqlQuery#mapRow(java.sql.ResultSet, int)
	 */
	@Override
	protected Object mapRow(ResultSet rs, int rowNum) throws SQLException {
		List<WeightedResource> resultRanking = new ArrayList<WeightedResource>();
		while (!rs.isAfterLast()){
			String urlAsString = rs.getString(4);
			URL url = null;
			if(urlAsString != null){
				try {
					url = new URL(urlAsString);
				} catch (MalformedURLException e) {
					logger.info("No URL created: " + urlAsString);
				}
			}
			resultRanking.add(new WeightedResource(ObjectFactory.getInMemoryResource(rs.getString(1), rs.getString(2), rs.getString(3), url, rs.getString(5)), rs.getDouble(6)));
			rs.next();
		}
		return resultRanking;
	}
	
}
